package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Destination;
import cn.wolfcode.wolf2world.domain.Travel;
import cn.wolfcode.wolf2world.domain.UserInfo;
import cn.wolfcode.wolf2world.exception.LogicException;
import cn.wolfcode.wolf2world.query.QueryType;
import cn.wolfcode.wolf2world.query.TravelQueryObject;
import cn.wolfcode.wolf2world.repository.TravelRepository;
import cn.wolfcode.wolf2world.service.DestinationService;
import cn.wolfcode.wolf2world.service.TravelService;
import cn.wolfcode.wolf2world.service.UserInfoService;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020-08-14 12:55
 */
@Service
public class TravelServiceImpl implements TravelService {
    @Autowired
    private TravelRepository travelRepository;
    @Autowired
    private DestinationService destinationService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void insert(Travel travel) {
        travel.setId(null);
        travelRepository.insert(travel);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Travel travel = travelRepository.findById(id).orElse(null);
        if (travel != null) {
            //游记关联的用户
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
            //游记关联的目的地
            Destination destination = destinationService.get(travel.getDestId());
            travel.setDest(destination);
        }

        return travel;
    }

    @Override
    public List<Travel> list() {
        return travelRepository.findAll();
    }

    /**
    * 前端旅游日记高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<Travel> query(TravelQueryObject qo) {
        Query query = new Query();
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("isPublic").is(1),
                Criteria.where("state").is(2)
        );
        query.addCriteria(criteria);
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (qo.getDayType() != null) {
            //QueryType queryType = QueryType.DAY_MAP.get(qo.getDayType());
            QueryType queryType = qo.getDayType();
            query.addCriteria(Criteria.where("day").gte(queryType.getMin()).lte(queryType.getMax()));
        }
        if (qo.getPerExpendType() != null) {
            QueryType queryType = qo.getPerExpendType();
            query.addCriteria(Criteria.where("perExpend").gte(queryType.getMin()).lte(queryType.getMax()));
        }
        if (qo.getOrderType() != null) {
            String queryType = qo.getOrderType();
            Page<Travel> page = DBHelper.getPage(mongoTemplate, query, qo, Travel.class, Sort.Direction.DESC, queryType);
            for (Travel travel : page) {
                String userId = travel.getUserId();
                UserInfo userInfo = userInfoService.get(userId);
                travel.setAuthor(userInfo);
            }
            return page;
        }
        Page<Travel> page = DBHelper.getPage(mongoTemplate, query, qo, Travel.class, Sort.Direction.ASC,"_id");
        for (Travel travel : page) {
            String userId = travel.getUserId();
            UserInfo userInfo = userInfoService.get(userId);
            travel.setAuthor(userInfo);
        }
        return page;
    }

    /**
     * 后端高级查询
     * @param qo
     * @return
     */
    @Override
    public Page<Travel> queryMgr(TravelQueryObject qo) {
        Query query = new Query();

        if (qo.getState() != null) {
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        Page<Travel> page = DBHelper.getPage(mongoTemplate, query, qo, Travel.class, Sort.Direction.ASC,"_id");
        for (Travel travel : page) {
            String userId = travel.getUserId();
            UserInfo userInfo = userInfoService.get(userId);
            travel.setAuthor(userInfo);
        }
        return page;
    }

    /**
     * 新增或编辑旅游日记
     * @param travel
     */
    @Override
    public void saveOrUpdate(Travel travel) {
        //维护数据
        //"destName":目的地名称
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());

        //"createTime":创建时间
        travel.setCreateTime(new Date());

        //"lastUpdateTime"最后更新时间
        travel.setLastUpdateTime(new Date());

        if (StringUtils.hasLength(travel.getId())) {
            Travel tv = this.get(travel.getId());
            //编辑
            //"viewnum":
            travel.setViewnum(tv.getViewnum());
            //"replynum":
            travel.setReplynum(tv.getReplynum());
            //"favornum":
            travel.setFavornum(tv.getFavornum());
            //"sharenum":
            travel.setSharenum(tv.getSharenum());
            //"thumbsupnum":
            travel.setThumbsupnum(tv.getThumbsupnum());
            this.update(travel);
        }else {
            //新增
            this.insert(travel);
        }
    }


    /**
     * 审核
     * @param id
     * @param state
     */
    @Override
    public void audit(String id, Integer state) {
        Travel travel = this.get(id);
        //是否满足什么条件
        if (travel == null || travel.getState()!=Travel.STATE_WAITING ) {
            throw new LogicException("数据异常");
        }

        //审核通过的操作
        if (state == Travel.STATE_RELEASE) {
            //游记状态改为发布
            travel.setState(Travel.STATE_RELEASE);
            //发布时间为当前时间
            travel.setReleaseTime(new Date());
            //跟新操作时间为当前时间
            travel.setLastUpdateTime(new Date());
        }else{
        //审核拒绝的操作
            //游记状态改为拒绝
            travel.setState(Travel.STATE_REJECT);
            //发布时间为null
            travel.setReleaseTime(null);
            //跟新操作时间为当前时间
            travel.setLastUpdateTime(new Date());
        }
        //更新
        this.update(travel);
    }

    /**
     * 下架
     * @param id
     * @param state
     */
    @Override
    public void up(String id, Integer state) {
        Travel travel = this.get(id);
        if (travel == null || travel.getState() != 2) {
            throw new LogicException("参数异常");
        }
        travel.setState(Travel.STATE_WAITING);
        travel.setIsPublic(Travel.ISPUBLIC_NO);
        //发布时间为null
        travel.setReleaseTime(null);
        //跟新操作时间为当前时间
        travel.setLastUpdateTime(new Date());
        this.update(travel);
    }

    /**
     * 与目的地相关的浏览量最高的前三
     * @param destId
     * @return
     */
    @Override
    public List<Travel> travelsViewnumTop3(String destId) {
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        List<Travel> list = travelRepository.findByDestId(destId,pageable);
        return list;
    }

    /**
     * 根据目的地名称查询游记
     * @param destName
     * @return
     */
    @Override
    public List<Travel> queryByDestName(String destName) {
        return travelRepository.findByDestName(destName);

    }

}
